package org.example.chatservice.consumer;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.chatservice.entity.ChatMessage;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class ChatMessageConsumer {
    private final SimpMessagingTemplate messagingTemplate;

    @RabbitListener(queues = "#{privateMessageQueue.name}")
    public void handlePrivateMessage(ChatMessage message) {
        try {
            messagingTemplate.convertAndSendToUser(
                message.getReceiverId(),
                "/queue/messages",
                message
            );
        } catch (Exception e) {
            log.error("Error processing private message: {}", e.getMessage());
            // 可以实现重试逻辑或将消息发送到死信队列
        }
    }

    @RabbitListener(queues = "#{groupMessageQueue.name}")
    public void handleGroupMessage(ChatMessage message) {
        try {
            messagingTemplate.convertAndSend(
                "/topic/group/" + message.getReceiverId(),
                message
            );
        } catch (Exception e) {
            log.error("Error processing group message: {}", e.getMessage());
        }
    }
}